package com.s54.auth;

import com.s54.api.system.UserApi;
import com.s54.common.beans.*;
import com.s54.common.enums.GlobalEnum;
import com.s54.common.exception.LoginException;
import com.s54.common.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@RequiredArgsConstructor
public class LoginService {
    private final UserApi userApi;
    private final TokenService tokenService;
    public Token login(LoginVO loginVO) {
        // 获取用户基本信息
        UserInfo userInfo = getUserInfo(loginVO);
        // 获取用户权限
        AuthUser authUser = getAuthUser(userInfo);

        return tokenService.createToken(authUser);
    }

    private AuthUser getAuthUser(UserInfo userInfo) {
        R<Set<String>> result = userApi.getApiPaths(userInfo.getUserName());
        if (result.isFailed()) {
            throw new LoginException(result.getMessage());
        }
        Set<String> apiPaths = result.getData();
        AuthUser authUser = new AuthUser();
        authUser.setNickName(userInfo.getNickName());
        authUser.setSex(userInfo.getSex());
        authUser.setUsername(userInfo.getUserName());
        authUser.setApiPaths(apiPaths);
        return authUser;
    }

    private UserInfo getUserInfo(LoginVO loginVO) {
        R<UserInfo> info = userApi.getUserInfo(loginVO.getUsername());
        if (info.isFailed()) {
            throw new LoginException(info.getMessage());
        }
        UserInfo userInfo = info.getData();
        if (!userInfo.getStatus().equals(GlobalEnum.STATUS_ENABLED.getValue())) {
            throw new LoginException("用户已禁用");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(loginVO.getPassword(), userInfo.getPassword())) {
            throw new LoginException("密码不正确");
        }
        return userInfo;
    }

    public Boolean logout(String accessToken) {
        return tokenService.removeToken(accessToken);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println("passwordEncoder.encode(\"123\") = " + passwordEncoder.encode("123"));
    }
}
